package com.lang.util;

import com.lang.DownloadConfig;
import com.lang.DownloadException;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Slf4j
public class DownloadFileUtil {

    /**
     * @param config 下载配置信息
     * @return 下载路径输出流
     */
    public static OutputStream savePathOutputStream(DownloadConfig config) {
        if (config.isDone()) {
            log.info("文件已下载完成 savePath={} url={}", config.getSavePath(), config.getUrl());
            return null;
        }
        Path savePath = Paths.get(config.getSavePath());
        try {
            if (Files.exists(savePath)) {
                if (savePath.toFile().length() > 0) {
                    if (config.isOverWrite()) {
                        if (!Files.deleteIfExists(savePath)) {
                            throw new DownloadException("删除源文件失败, 无法覆盖下载文件, savepath=" + config.getSavePath());
                        }
                    } else {
                        log.info("文件已存在,且策略设置为不覆盖源文件");
                        return null;
                    }
                }
            }
            return Files.newOutputStream(savePath);
        } catch (IOException e) {
            throw new DownloadException("获取文件输出流失败 savePath=" + config.getSavePath());
        }
    }

}
